import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import { storeLogger } from '@/utils/logger'

export const useRedisTaskMonitorStore = defineStore('redisTaskMonitor', () => {
  // ============================================================================
  // 环境配置（仅保留下拉列表以兼容其它组件）
  // ============================================================================
  const envConfigsList = ref([]) // 所有环境列表（用于下拉选择，仅保留）

  // ============================================================================
  // 任务监控配置状态
  // ============================================================================
  const taskConfigs = ref([])
  const taskConfigsLoading = ref(false)
  const taskConfigsTotal = ref(0)
  const taskConfigsPage = ref(1)
  const taskConfigsPageSize = ref(20)
  const taskConfigsStats = ref({})
  const taskConfigCategories = ref([])
  const taskConfigKeyPrefixes = ref([])

  // ============================================================================
  // 任务数据状态
  // ============================================================================
  const taskData = ref([])
  const taskDataLoading = ref(false)
  const taskDataTotal = ref(0)
  const taskDataPage = ref(1)
  const taskDataPageSize = ref(20)
  const taskDataStats = ref({})

  // ============================================================================
  // 队列监控配置状态
  // ============================================================================
  const queueConfigs = ref([])
  const queueConfigsLoading = ref(false)
  const queueConfigsTotal = ref(0)
  const queueConfigsPage = ref(1)
  const queueConfigsPageSize = ref(20)
  const queueConfigsStats = ref({})
  const queueConfigCategories = ref([])
  const queueConfigQueueKeys = ref([])

  // ============================================================================
  // 队列统计数据状态
  // ============================================================================
  const queueStats = ref([])
  const queueStatsLoading = ref(false)
  const queueStatsTotal = ref(0)
  const queueStatsPage = ref(1)
  const queueStatsPageSize = ref(20)
  const queueStatsTrend = ref([])
  const queueStatsSummary = ref({})

  // ============================================================================
  // 爬虫状态状态
  // ============================================================================
  const spiderStatus = ref([])
  const spiderStatusLoading = ref(false)
  const spiderStatusTotal = ref(0)
  const spiderStatusPage = ref(1)
  const spiderStatusPageSize = ref(20)
  const spiderStatusStats = ref({})

  // ============================================================================
  // 环境配置 API
  // ============================================================================

  // 获取所有环境配置列表（用于下拉选择）
  const fetchEnvConfigsList = async () => {
    // 空实现：保持兼容，返回空数组
    envConfigsList.value = []
    storeLogger.info('环境配置列表（全部）已移除，返回空列表用于兼容', { count: 0 })
    return { success: true, data: { items: [] } }
  }

  // ============================================================================
  // 任务监控配置 API
  // ============================================================================

  // 获取任务配置列表
  const fetchTaskConfigs = async (params = {}) => {
    try {
      taskConfigsLoading.value = true
      const queryParams = {
        page: taskConfigsPage.value,
        pageSize: taskConfigsPageSize.value,
        ...params
      }

      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      const response = await api.get('/redis-task-monitor/configs', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      taskConfigs.value = data.items || []
      taskConfigsTotal.value = data.total || 0
      taskConfigsPage.value = data.page || 1
      taskConfigsPageSize.value = data.pageSize || 20

      if (data.stats) {
        taskConfigsStats.value = data.stats
      }

      storeLogger.info('任务配置列表获取成功', {
        count: taskConfigs.value.length,
        total: taskConfigsTotal.value
      })

      return response.data
    } catch (error) {
      storeLogger.error('获取任务配置列表失败', error)
      throw error
    } finally {
      taskConfigsLoading.value = false
    }
  }

  // 获取任务配置分类列表
  const fetchTaskConfigCategories = async () => {
    try {
      const response = await api.get('/redis-task-monitor/configs/categories')
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      taskConfigCategories.value = data.items || []

      return response.data
    } catch (error) {
      storeLogger.error('获取任务配置分类列表失败', error)
      throw error
    }
  }

  // 获取任务配置key前缀列表
  const fetchTaskConfigKeyPrefixes = async () => {
    try {
      const response = await api.get('/redis-task-monitor/configs/key-prefixes')
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      taskConfigKeyPrefixes.value = data.items || []

      return response.data
    } catch (error) {
      storeLogger.error('获取任务配置key前缀列表失败', error)
      throw error
    }
  }

  // 获取任务配置详情
  const fetchTaskConfig = async (configId) => {
    try {
      const response = await api.get(`/redis-task-monitor/configs/${configId}`)
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      return data
    } catch (error) {
      storeLogger.error('获取任务配置详情失败', error)
      throw error
    }
  }

  // 创建任务配置
  const createTaskConfig = async (data) => {
    try {
      taskConfigsLoading.value = true
      const response = await api.post('/redis-task-monitor/configs', data)
      
      if (response.data.success) {
        ElMessage.success('任务配置创建成功')
        await fetchTaskConfigs()
      }

      return response.data
    } catch (error) {
      storeLogger.error('创建任务配置失败', error)
      throw error
    } finally {
      taskConfigsLoading.value = false
    }
  }

  // 更新任务配置
  const updateTaskConfig = async (configId, data) => {
    try {
      taskConfigsLoading.value = true
      const response = await api.put(`/redis-task-monitor/configs/${configId}`, data)
      
      if (response.data.success) {
        ElMessage.success('任务配置更新成功')
        await fetchTaskConfigs()
      }

      return response.data
    } catch (error) {
      storeLogger.error('更新任务配置失败', error)
      throw error
    } finally {
      taskConfigsLoading.value = false
    }
  }

  // 删除任务配置
  const deleteTaskConfig = async (configId) => {
    try {
      taskConfigsLoading.value = true
      const response = await api.delete(`/redis-task-monitor/configs/${configId}`)
      
      if (response.data.success) {
        ElMessage.success('任务配置删除成功')
        await fetchTaskConfigs()
      }

      return response.data
    } catch (error) {
      storeLogger.error('删除任务配置失败', error)
      throw error
    } finally {
      taskConfigsLoading.value = false
    }
  }

  // ============================================================================
  // 任务数据 API
  // ============================================================================

  // 获取任务数据列表
  const fetchTaskData = async (params = {}) => {
    try {
      taskDataLoading.value = true
      const queryParams = {
        page: taskDataPage.value,
        pageSize: taskDataPageSize.value,
        ...params
      }

      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      const response = await api.get('/redis-task-monitor/task-data', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      taskData.value = data.items || []
      taskDataTotal.value = data.total || 0
      taskDataPage.value = data.page || 1
      taskDataPageSize.value = data.pageSize || 20

      storeLogger.info('任务数据列表获取成功', {
        count: taskData.value.length,
        total: taskDataTotal.value
      })

      return response.data
    } catch (error) {
      storeLogger.error('获取任务数据列表失败', error)
      throw error
    } finally {
      taskDataLoading.value = false
    }
  }

  // 获取任务数据详情
  const fetchTaskDataDetail = async (dataId) => {
    try {
      const response = await api.get(`/redis-task-monitor/task-data/${dataId}`)
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      return data
    } catch (error) {
      storeLogger.error('获取任务数据详情失败', error)
      throw error
    }
  }

  // 获取任务数据统计
  const fetchTaskDataStats = async (params = {}) => {
    try {
      const queryParams = { ...params }

      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      const response = await api.get('/redis-task-monitor/task-data/stats', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      taskDataStats.value = data || {}

      return response.data
    } catch (error) {
      storeLogger.error('获取任务数据统计失败', error)
      throw error
    }
  }

  // ============================================================================
  // 队列监控配置 API
  // ============================================================================

  // 获取队列配置列表
  const fetchQueueConfigs = async (params = {}) => {
    try {
      queueConfigsLoading.value = true
      const queryParams = {
        page: queueConfigsPage.value,
        pageSize: queueConfigsPageSize.value,
        ...params
      }

      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      const response = await api.get('/redis-queue-monitor/configs', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      queueConfigs.value = data.items || []
      queueConfigsTotal.value = data.total || 0
      queueConfigsPage.value = data.page || 1
      queueConfigsPageSize.value = data.pageSize || 20

      if (data.stats) {
        queueConfigsStats.value = data.stats
      }

      storeLogger.info('队列配置列表获取成功', {
        count: queueConfigs.value.length,
        total: queueConfigsTotal.value
      })

      return response.data
    } catch (error) {
      storeLogger.error('获取队列配置列表失败', error)
      throw error
    } finally {
      queueConfigsLoading.value = false
    }
  }

  // 获取队列配置分类列表
  const fetchQueueConfigCategories = async () => {
    try {
      const response = await api.get('/redis-queue-monitor/configs/categories')
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      queueConfigCategories.value = data.items || []

      return response.data
    } catch (error) {
      storeLogger.error('获取队列配置分类列表失败', error)
      throw error
    }
  }

  // 获取队列配置队列key列表
  const fetchQueueConfigQueueKeys = async () => {
    try {
      const response = await api.get('/redis-queue-monitor/configs/queue-keys')
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      queueConfigQueueKeys.value = data.items || []

      return response.data
    } catch (error) {
      storeLogger.error('获取队列配置队列key列表失败', error)
      throw error
    }
  }

  // 获取队列配置详情
  const fetchQueueConfig = async (configId) => {
    try {
      const response = await api.get(`/redis-queue-monitor/configs/${configId}`)
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      return data
    } catch (error) {
      storeLogger.error('获取队列配置详情失败', error)
      throw error
    }
  }

  // 创建队列配置
  const createQueueConfig = async (data) => {
    try {
      queueConfigsLoading.value = true
      const response = await api.post('/redis-queue-monitor/configs', data)
      
      if (response.data.success) {
        ElMessage.success('队列配置创建成功')
        await fetchQueueConfigs()
      }

      return response.data
    } catch (error) {
      storeLogger.error('创建队列配置失败', error)
      throw error
    } finally {
      queueConfigsLoading.value = false
    }
  }

  // 更新队列配置
  const updateQueueConfig = async (configId, data) => {
    try {
      queueConfigsLoading.value = true
      const response = await api.put(`/redis-queue-monitor/configs/${configId}`, data)
      
      if (response.data.success) {
        ElMessage.success('队列配置更新成功')
        await fetchQueueConfigs()
      }

      return response.data
    } catch (error) {
      storeLogger.error('更新队列配置失败', error)
      throw error
    } finally {
      queueConfigsLoading.value = false
    }
  }

  // 删除队列配置
  const deleteQueueConfig = async (configId) => {
    try {
      queueConfigsLoading.value = true
      const response = await api.delete(`/redis-queue-monitor/configs/${configId}`)
      
      if (response.data.success) {
        ElMessage.success('队列配置删除成功')
        await fetchQueueConfigs()
      }

      return response.data
    } catch (error) {
      storeLogger.error('删除队列配置失败', error)
      throw error
    } finally {
      queueConfigsLoading.value = false
    }
  }

  // ============================================================================
  // 队列统计数据 API
  // ============================================================================

  // 获取队列统计数据列表
  const fetchQueueStats = async (params = {}) => {
    try {
      queueStatsLoading.value = true
      const queryParams = {
        page: queueStatsPage.value,
        pageSize: queueStatsPageSize.value,
        ...params
      }

      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      const response = await api.get('/redis-queue-monitor/stats', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      queueStats.value = data.items || []
      queueStatsTotal.value = data.total || 0
      queueStatsPage.value = data.page || 1
      queueStatsPageSize.value = data.pageSize || 20

      storeLogger.info('队列统计数据列表获取成功', {
        count: queueStats.value.length,
        total: queueStatsTotal.value
      })

      return response.data
    } catch (error) {
      storeLogger.error('获取队列统计数据列表失败', error)
      throw error
    } finally {
      queueStatsLoading.value = false
    }
  }

  // 获取队列统计数据详情
  const fetchQueueStatsDetail = async (statsId) => {
    try {
      const response = await api.get(`/redis-queue-monitor/stats/${statsId}`)
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      return data
    } catch (error) {
      storeLogger.error('获取队列统计数据详情失败', error)
      throw error
    }
  }

  // 获取队列统计数据趋势
  const fetchQueueStatsTrend = async (params = {}) => {
    try {
      const queryParams = { ...params }

      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      const response = await api.get('/redis-queue-monitor/stats/trend', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      queueStatsTrend.value = data.items || []

      return response.data
    } catch (error) {
      storeLogger.error('获取队列统计数据趋势失败', error)
      throw error
    }
  }

  // 获取队列统计数据摘要
  const fetchQueueStatsSummary = async (params = {}) => {
    try {
      const queryParams = { ...params }

      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      const response = await api.get('/redis-queue-monitor/stats/summary', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      queueStatsSummary.value = data || {}

      return response.data
    } catch (error) {
      storeLogger.error('获取队列统计数据摘要失败', error)
      throw error
    }
  }

  // ============================================================================
  // 爬虫状态 API
  // ============================================================================

  // 获取爬虫状态列表
  const fetchSpiderStatus = async (params = {}) => {
    try {
      spiderStatusLoading.value = true
      const queryParams = {
        page: spiderStatusPage.value,
        pageSize: spiderStatusPageSize.value,
        ...params
      }

      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      const response = await api.get('/redis-queue-monitor/spiders', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      spiderStatus.value = data.items || []
      spiderStatusTotal.value = data.total || 0
      spiderStatusPage.value = data.page || 1
      spiderStatusPageSize.value = data.pageSize || 20

      storeLogger.info('爬虫状态列表获取成功', {
        count: spiderStatus.value.length,
        total: spiderStatusTotal.value
      })

      return response.data
    } catch (error) {
      storeLogger.error('获取爬虫状态列表失败', error)
      throw error
    } finally {
      spiderStatusLoading.value = false
    }
  }

  // 获取爬虫状态详情
  const fetchSpiderStatusDetail = async (spiderId) => {
    try {
      const response = await api.get(`/redis-queue-monitor/spiders/${spiderId}`)
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      return data
    } catch (error) {
      storeLogger.error('获取爬虫状态详情失败', error)
      throw error
    }
  }

  // 获取爬虫状态统计
  const fetchSpiderStatusStats = async (params = {}) => {
    try {
      const queryParams = { ...params }

      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      const response = await api.get('/redis-queue-monitor/spiders/stats', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload

      spiderStatusStats.value = data || {}

      return response.data
    } catch (error) {
      storeLogger.error('获取爬虫状态统计失败', error)
      throw error
    }
  }

  // 更新爬虫心跳
  const updateSpiderHeartbeat = async (spiderId, data = {}) => {
    try {
      const response = await api.put(`/redis-queue-monitor/spiders/${spiderId}/heartbeat`, data)
      
      if (response.data.success) {
        ElMessage.success('爬虫心跳更新成功')
        await fetchSpiderStatus()
      }

      return response.data
    } catch (error) {
      storeLogger.error('更新爬虫心跳失败', error)
      throw error
    }
  }

  // ============================================================================
  // 导出
  // ============================================================================

  return {
    // 环境配置（仅兼容性：全量列表）
    envConfigsList,
    fetchEnvConfigsList,

    // 任务监控配置
    taskConfigs,
    taskConfigsLoading,
    taskConfigsTotal,
    taskConfigsPage,
    taskConfigsPageSize,
    taskConfigsStats,
    taskConfigCategories,
    taskConfigKeyPrefixes,
    fetchTaskConfigs,
    fetchTaskConfigCategories,
    fetchTaskConfigKeyPrefixes,
    fetchTaskConfig,
    createTaskConfig,
    updateTaskConfig,
    deleteTaskConfig,

    // 任务数据
    taskData,
    taskDataLoading,
    taskDataTotal,
    taskDataPage,
    taskDataPageSize,
    taskDataStats,
    fetchTaskData,
    fetchTaskDataDetail,
    fetchTaskDataStats,

    // 队列监控配置
    queueConfigs,
    queueConfigsLoading,
    queueConfigsTotal,
    queueConfigsPage,
    queueConfigsPageSize,
    queueConfigsStats,
    queueConfigCategories,
    queueConfigQueueKeys,
    fetchQueueConfigs,
    fetchQueueConfigCategories,
    fetchQueueConfigQueueKeys,
    fetchQueueConfig,
    createQueueConfig,
    updateQueueConfig,
    deleteQueueConfig,

    // 队列统计数据
    queueStats,
    queueStatsLoading,
    queueStatsTotal,
    queueStatsPage,
    queueStatsPageSize,
    queueStatsTrend,
    queueStatsSummary,
    fetchQueueStats,
    fetchQueueStatsDetail,
    fetchQueueStatsTrend,
    fetchQueueStatsSummary,

    // 爬虫状态
    spiderStatus,
    spiderStatusLoading,
    spiderStatusTotal,
    spiderStatusPage,
    spiderStatusPageSize,
    spiderStatusStats,
    fetchSpiderStatus,
    fetchSpiderStatusDetail,
    fetchSpiderStatusStats,
    updateSpiderHeartbeat,

    // 批次记录（已移除，保留空）
  }
})

